package org.yx.service.sres.save_device_resource;

import org.yx.exception.BizException;
import org.yx.models.SresDevDef;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 保存设备资源台账（新增，修改，删除操作）
 * 
 * @author zxw
 * @since 2019/06/12
 **/
public class SresSaveDeviceResourceService extends BaseService {
	public SresSaveDeviceResourceOut saveDeviceResource(
			SresSaveDeviceResourceIn in) throws Exception {
		if (StrUtil.isBlank(in.getResId())) {
			throw new BizException("SYS-0004",
					FieldMap.of("parameter", "resId"));
		}

		String fileId = null;
		if (in.getResStatus() != null && 'D' == in.getResStatus()) {
			// delete
			SresDevDef res = selectOneLocked(SresDevDef.class,
					in.getUserOrgCode(), in.getResId());
			if (res == null || res.getResStatus() == 'D') {
				throw new BizException("SRES-0001", "此资源${resId}不存在或已经删除。",
						FieldMap.of("resId", in.getResId()));
			}

			res.setResStatus('D');

			update(res, "resStatus");

		} else {
			// insert or update
			SresDevDef res = selectOneLocked(SresDevDef.class,
					in.getUserOrgCode(), in.getResId());
			if (res != null) {
				if (res.getResStatus() == 'D') {
					throw new BizException("SRES-0001", "此资源${resId}不存在或已经删除。",
							FieldMap.of("resId", in.getResId()));
				}

				copyProperties(in, res);

				update(res);
			} else {
				res = new SresDevDef();
				copyProperties(in, res);
				res.setOrgCode(in.getUserOrgCode());
				res.setResStatus('N');

				insert(res);
			}
		}

		SresSaveDeviceResourceOut out = new SresSaveDeviceResourceOut();
		out.setFileId(fileId);
		return out;
	}
}